package demo;

import api.GreetingServiceAsync;
import api.GreetingServiceRpcContext;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.rpc.AsyncContext;
import org.apache.dubbo.rpc.RpcContext;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Copyright (c)  by www.leya920.com
 * All right reserved.
 * Create Date: 2020-11-21 16:54
 * Create Author: xuweiwei
 * File Name: GreetingServiceAsyncImpl.java
 * Last version:  1.0
 * Function: //TODO
 * Last Update Date: 2020-11-21 16:54
 * Last Update Log:
 * Comment: 服务提供方 异步执行代码
 **/
public class GreetingServiceAsyncContextImpl implements GreetingServiceRpcContext {

    // 创建业务自定义线程池
    private final ThreadPoolExecutor bizThreadPool = new ThreadPoolExecutor(8, 16, 1,
            TimeUnit.MINUTES,
            new SynchronousQueue<>(),
            new NamedThreadFactory("biz-thread-pool"),
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    // 创建服务处理接口  返回值为CompletableFuture
    @Override
    public String sayHello(String name) {

        // 1 开启异步
        final AsyncContext asyncContext = RpcContext.startAsync();

        bizThreadPool.execute(() -> {
            asyncContext.signalContextSwitch();

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            asyncContext.write("hello async context" + name + " " + RpcContext.getContext().getAttachment("company"));
        });

        return null;
    }
}
